﻿using System;
using System.Collections.Generic;
using System.Text;
using PluginCore;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using MUnitGenerator.Helpers;

namespace MUnitGenerator.Actions
{
    class RunCurrentTestAction : RunTestActionBase
    {
        public RunCurrentTestAction(PluginMain main, Settings settingObject) : base(main, settingObject)
        {
        }

        protected override void Execute()
        {
            CreateTestPathsIfNeed();

            string filePath = PluginBase.MainForm.CurrentDocument.FileName;
            string testsSrcPath = Path.Combine(GetTestsPath(), TestPaths.SrcName);
            if (!IsTestCasePath(filePath))
            {
                ProcessDefault();
                return;
            }

            List<string> listWithFullClassName;
            string fullClassName;
            {
                filePath = filePath.Replace(testsSrcPath, "");
                if (filePath.IndexOf(Path.DirectorySeparatorChar) == 0)
                {
                    filePath = filePath.Substring(1);
                }
                filePath = filePath.Replace(Path.GetExtension(filePath), "");
                fullClassName = filePath.Replace(Path.DirectorySeparatorChar, '.');

                listWithFullClassName = new List<string>();
                listWithFullClassName.Add(fullClassName);
            }

            TestTarget target;
            {
                var sci = PluginBase.MainForm.CurrentDocument.SciControl;
                target = TestTargetHelper.GetTargetUnderCursor(sci.Text, sci.CurrentPos);
            }

            switch (target.type)
            {
                case TestTargetType.Class:
                    if (fullClassName.EndsWith(target.ClassName))
                    {
                        GenerateTestSuteAndRun(listWithFullClassName, false);
                    }
                    else
                    {
                        ProcessDefault();
                    }
                    break;
                case TestTargetType.Method:
                    GenerateTestSuteAndRun(listWithFullClassName, target.MethodName);
                    break;
                case TestTargetType.Nothing:
                    ProcessDefault();
                    break;
            }
        }

        private bool IsTestCasePath(string filePath)
        {
            return filePath.IndexOf(Path.Combine(GetTestsPath(), TestPaths.SrcName)) == 0 &&
                filePath.IndexOf("Test.hx") != -1;
        }

        private void ProcessDefault()
        {
            GenerateTestSuteAndRun(FindTestCasesRecursively(), true);
        }
    }
}
